package com.kust.smarhome.background.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kust.smarhome.background.common.lang.Result;
import com.kust.smarhome.background.common.vo.CommodityVo;
import com.kust.smarhome.background.common.vo.MoneyVo;
import com.kust.smarhome.background.model.Commodity;
import com.kust.smarhome.background.model.OrderForm;
import com.kust.smarhome.background.service.ICommodityService;
import com.kust.smarhome.background.service.IOrderFormService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author iAuzre
 * @since 2021-07-31
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController extends BaseController {

    @Resource
    private ICommodityService commodityService;

    @Resource
    private IOrderFormService orderFormService;

    @GetMapping("/list")
    public Result list(@Validated CommodityVo commodityVo, BindingResult result, Principal principal) {

        if (result.hasErrors())
            return Result.fail(result.getFieldError().getDefaultMessage());

        if (getUserPower(principal.getName()))
            return Result.fail(401, "权限不足", null);


        Page<Commodity> page = commodityService.page(getPage(), new QueryWrapper<Commodity>()
                .like(StrUtil.isNotBlank(commodityVo.getName()), "name", commodityVo.getName())
                .eq(commodityVo.getStatus() != 10, "status", commodityVo.getStatus())
        );

        return Result.succ(page);

    }

    @GetMapping("/{id}/ban")
    public Result ban(@PathVariable Integer id, Principal principal) {

        if (getUserPower(principal.getName()))
            return Result.fail(401, "权限不足", null);

        Commodity commodity = commodityService.getById(id);
        if (commodity == null)
            return Result.fail("商品不存在");

        commodity.setIsAdded(0);

        if (!commodityService.updateById(commodity))
            return Result.fail("系统错误");

        return Result.succ(null);
    }

    @GetMapping("/{id}/banOff")
    public Result banOff(@PathVariable Integer id, Principal principal) {

        if (getUserPower(principal.getName()))
            return Result.fail(401, "权限不足", null);

        Commodity commodity = commodityService.getById(id);
        if (commodity == null)
            return Result.fail("商品不存在");

        commodity.setIsAdded(1);

        if (!commodityService.updateById(commodity))
            return Result.fail("系统错误");

        return Result.succ(null);
    }

    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestBody Integer[] ids, Principal principal) {

        if (getUserPower(principal.getName()))
            return Result.fail(401, "权限不足", null);

        for (int id : ids) {
            commodityService.removeById(id);
        }

        return Result.succ(null);
    }

    @PostMapping("/setMoney")
    public Result setMoney(@RequestBody @Validated MoneyVo moneyVo, BindingResult result, Principal principal) {

        if (result.hasErrors())
            return Result.fail(result.getFieldError().getDefaultMessage());

        if (getUserPower(principal.getName()))
            return Result.fail(401, "权限不足", null);

        Commodity commodity = commodityService.getById(moneyVo.getId());
        commodity.setMoney(moneyVo.getMoney());

        if (!commodityService.updateById(commodity))
            return Result.fail(500, "系统错误", null);

        return Result.succ(null);
    }

    @GetMapping("/getShopData")
    public Result getShopData(Principal principal) {

        if (getUserPower(principal.getName()))
            return Result.fail(401, "没有权限", null);

        //获取每个商品的销量,用map保存<Integer(id), Integer(销量)>
        Map<Integer, Integer> numberMap = new HashMap<>();
        List<OrderForm> orderForms = orderFormService.list();
        for (OrderForm orderForm : orderForms) {
            String[] commodityIds = orderForm.getCommodityId().split(";");
            String[] commodityNumber = orderForm.getCommodityNumber().split(";");

            for (int i = 0; i < commodityIds.length; i++) {
                int id = Integer.parseInt(commodityIds[i]);
                int num = Integer.parseInt(commodityNumber[i]);

                if (numberMap.get(id) == null || numberMap.get(id) == 0) {
                    numberMap.put(id, num);
                } else {
                    int number = numberMap.get(id) + num;
                    numberMap.put(id, number);
                }
            }
        }

        List<Commodity> commodities = commodityService.list();
        List<String> commodityName = new ArrayList<>();
        List<Integer> commodityNum = new ArrayList<>();
        for (Commodity commodity : commodities) {
            commodityName.add(commodity.getName());
            commodityNum.add(numberMap.get(commodity.getId()));
        }

        for (int i = 0; i < commodityNum.size(); i++) {
            if (commodityNum.get(i) == null) {
                commodityNum.set(i, 0);
            }
        }

        return Result.succ(MapUtil.builder()
                .put("name", commodityName)
                .put("num", commodityNum)
                .map()
        );
    }

}
